﻿var SERVER_ADDRESS = "";
var OldStopIco = null;
var OldStopIco2 = null;
var BusId = "";
var RouteId = 0;
var StopId = 0;
var RouteTo="";
var MarkerObj = null;
var MarkerData = null;
var StopData = null;
var AlarmData = null;
var RouteName = "";
var Goto = 0;
var City = "";
var weather = "";
var HeaderItem = new Array("","","");
var HeaderTimeObj = null;
var getNextStopTime = null;
var thisPage = "";
/*當前自已坐標*/
var mylon = 0;
var mylat = 0;
/*讀取數據*/
function GetHTML(t, url, sc, ec, as) {
    $.ajax({
        type: 'get',
        async:as,
        dataType: t,
        url: url,
        timeout: 5000,
        success: sc,
        error: ec,
        complete: function() { }
    });
}
/*初始化參數*/
function Init(rid, gob, _city,_busid) {
    if (rid != "") {
        RouteId = rid;
        Goto = gob;
        City = _city;
        BusId = _busid;
        window.localStorage.setItem("BusId", _busid);
        window.localStorage.setItem("RouteId", rid);
        window.localStorage.setItem("Goto", gob);
        window.localStorage.setItem("City", _city);
    }
    else {
        RouteId = window.localStorage.getItem("RouteId");
        BusId = window.localStorage.getItem("BusId");
        RouteName=window.localStorage.getItem("RouteName");
        Goto=window.localStorage.getItem("Goto");
        City = window.localStorage.getItem("City");
        $("#route_Name").html(RouteName);
    }
}
function InitCallBack(result) {
    RouteName = result.route.name;
    RouteTo=result.route.to;
    window.localStorage.setItem("RouteName", RouteName);
    HeaderItem[0] = '<li><img src="icon/bus4.png" border="0" class="icon_bus" />' + RouteName + '開往' + RouteTo + '</li>';
    header_info();

    $.each(result.stop, function(index, rs) {
        var ico = "";
        $.each(rs.marker_class, function(index2, rs2) {
            ico += "<img src='icon/" + rs2.id + "_min.png'>";
        });
        $("#stop" + rs.id + " .icon").html(ico);
    });
    
}
function InitError(err) { }
/*獲取站牌*/
function GetStop(rid, city, gob) {
    GetHTML("json", SERVER_ADDRESS + "/Service/RouteStop.aspx?rtid=" + rid + "&city=" + city + "&gob="+gob, GetStopSucceed, GetStopError,true);
}
function GetStopSucceed(result) {
    try {
        var list = ""
        OldStopIco = null;
        OldStopNews = null;
        $.each(result, function(index, rs) {
            list += '<div class="bubble bubble-news" id="stop' + rs.id + '">' +
		    '<div class="bus first">' +
		    '	<img src="icon/bus2.gif" id="ico' + rs.id + '" border="0" />' +
		    '</div>' +
		    '<div class="arrow1"></div>' +
		    '<div class="content-wrapper" stop=true stopid="' + rs.id + '" stopname="' + rs.name + '" lat="' + rs.lat + '" lon="' + rs.lng + '">' +
		    '	<div class="content">' +
		    '		<div class="title" id="title' + rs.id + '">' + rs.name + '</div>' +
		    '			<ul class="icon">' +
		    '			</ul>' +
		    '			<div class="avatar"></div>' +
		    '			<div class="text"></div>' +
		    '	</div>' +
		    '</div>' +
		    '<br clear="all" />' +
	        '</div>';
        });
        $("#StopList").empty();
        $("#StopList").html(list);
        $("div[stop=true]").live("click", function(e) {
            StopId = this.getAttribute("stopid");
            var slat = this.getAttribute("lat");
            var slng = this.getAttribute("lon");
            var name = this.getAttribute("stopname");
            StopData = { id: StopId, lat: slat, lng: slng, name: name }
            //RemoveInfo(1);
            //GetHTML("json", SERVER_ADDRESS + "/Service/Weather.aspx?lat=" + slat + "&lng=" + slng, GetWeatherSucceed, null, false);
            //HeaderItem[1] = '<li><div style="float:left"><img src="icon/bus4.png" border="0" class="icon_bus" />' + name + '</div><div  style="float:right;padding:5px 5px 0px 0px;text-align:center">' + weather + '</div></li>';
            //HeaderItem.push({ id: 1, msg: '<li><div style="float:left"><img src="icon/bus4.png" border="0" class="icon_bus" />' + $("#title" + StopId).html() + '</div><div  style="float:right;padding:5px 5px 0px 0px;text-align:center">' + weather + '</div></li>' });
            $.mobile.changePage("marker.aspx?stid=" + StopId, { transition: "slide",reverse :true});
        });
        window.setTimeout("SetCarLocation()", 100);
        GetHTML("json", SERVER_ADDRESS + "/Service/RouteMarker.aspx?rtid=" + RouteId + "&city=" + City + "&gob=" + Goto, InitCallBack, InitError,true);
    }
    catch (e) { alert(e.message)}
}
function GetStopError(err) {
    alert("獲取線路失敗");
}
function GetWeatherSucceed(result) {
    weather = result.current_conditions.condition + " " + result.current_conditions.temp_c + "&deg;C";
}
/*設置站點標識*/
function SetStopIco(id, flag) {
    if (OldStopIco != null)
        OldStopIco.attr("src", "icon/bus2.gif");
    $("#ico" + id).attr("src", "icon/bus" + flag + ".gif");
    OldStopIco = $("#ico" + id);
    $("html,body").animate({ scrollTop: OldStopIco.offset().top - 70 }, 1000);
}
function SetStopIco2(id, flag) {
    if (OldStopIco2 != null)
        OldStopIco2.attr("src", "icon/bus2.gif");
    if (flag != -1) {
        $("#ico" + id).attr("src", "icon/bus" + flag + ".gif");
        OldStopIco2 = $("#ico" + id);
    }
    else
        OldStopIco2 = null;
}

/*設置加News*/
function SetStopNews(id) {
    //if (OldStopNews != null)
    //    OldStopNews.removeClass("new");
    $("#stop" + id).addClass("new");
   // OldStopNews = $("#stop" + id);
}
/*開始驗證當前坐標*/
function SetCarLocation() {
    if ($.mobile.activePage.attr("id") == "chatpage") {
        var index = GetMyLocation();
        if (index >= 1) {
            SetStopIco(index, 1);
        }
    }
}
/*獲取最近的站牌*/
function GetMyLocation() {
    var nearestIndex = 0;
    var minDist = 1;
    $("div[stop=true]").each(function(i, rs) {
        var lat = parseFloat($(rs).attr("lat"));
        var lng = parseFloat($(rs).attr("lon"));
        if (lat != 0) {
            var dist = Math.abs(mylon - lng) + Math.abs(mylat - lat);
            if (dist < minDist) {
                minDist = dist;
                nearestIndex = $(rs).attr("stopid");
            }
        }
    })
    return nearestIndex;
}
/*獲取坐標*/
function get_location() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(get_location_callback, handle_error, { enableHighAccuracy: true, maximumAge: 30000, timeout: 27000 });
    } else {
        alert("geoLocation Error!");
    }
}
function get_location_callback(position) {
    mylat = position.coords.latitude;
    mylon = position.coords.longitude;
}
function handle_error(err) {
    alert("獲取坐標失敗");
}
/*獲取地標*/
function get_marker(sid) {
    GetHTML("json", SERVER_ADDRESS + "/Service/StopMarker.aspx?stid=" + StopId+"&city="+City+"&info=marker.photo", get_marker_succeed, get_marker_error,true)
}
function get_marker_succeed(result) {
    var list = "";
    var oldClass = "";
    var oldIndex = 0;
    var i=0;
    MarkerData = new Array();
    google_initialize(result.stop.lat, result.stop.lng);
    $.each(result.marker, function(index, rs) {
        if (oldClass != rs.class_id) {
            list += '<div class="bar"><div class="bar_left">' +
		    '    <img src="icon/' + rs.class_id + '.png" border="0" />' +
		    '    <div class="text123">' + rs.class_name + '</div></div>' +
	        '<div class="bar_line">&nbsp;0</div></div>' +
	        '<br clear="all" />';
            oldClass = rs.class_id;
            oldIndex = 0;
        }
        var icoName = rs.class_id + '_' + oldIndex;
        list += '<div class="bar-box">' +
		'<div class="bar-img">' +
		'	<img src="icon/' + icoName + '.png" border="0" />' +
		'</div>' +
		'<div class="arrow1"></div>' +
		'<div class="content-wrapper" index="'+i+'" marker=true markerid="' + rs.id + '" lat="' + rs.lat + '" lng="' + rs.lng + '" ico="' + icoName + '">' +
		'	<div class="content">' +
		'		<div class="bar-image" style="float:left;"><img src="http://maps.googleapis.com/maps/api/streetview?size=77x65&location=' + rs.lat + ',%20' + rs.lng + '&heading=0&fov=140&pitch=-10&sensor=false&key=AIzaSyB5ygYaDOar7qCHWLTWPmzh1-XYkoPdXkw" border="0" /></div>' +
		'		<div class="text" style="margin-left:55px;"><span class="title">' + rs.name + '</span><br />' + rs.desc + '</div>' +
		'	</div>' +
		'</div>' +
		'<br clear="all" />' +
	    '</div>';
        AddMarker(rs.lat, rs.lng, icoName);
        MarkerData.push(rs);
        oldIndex++;
        i++;
    });
    $("#marker_list").html(list);
    $("#marker_list div[marker=true]").live("click", function(e) {
        var mid = this.getAttribute("markerid");
        var mlat = this.getAttribute("lat");
        var mlng = this.getAttribute("lng");
        var mico = this.getAttribute("ico");
        var mindex = this.getAttribute("index");
        MarkerObj = { id: mid, lat: mlat, lng: mlng, ico: mico, index: mindex }
        $.mobile.changePage("marker_detail.aspx", { transition: "slide", reverse: true });
    });
}
function get_marker_error(err) {
    //alert("獲取坐標失敗");
}
function RemoveInfo(id) {
    /*for (k = 0; k < HeaderItem.length; k++) {
        if (HeaderItem[k].id == id) {
            alert(HeaderItem[k].id);
            HeaderItem.splice(k,1);
            break;
        }
    }*/
    HeaderItem[id] = "";
}
function header_info(flag) {
    var str = "";
    var obj = $("#" + thisPage + " .head_bar ul");
    obj.empty();
    var count = 0;
    $.each(HeaderItem, function(index, rs) {
        str += rs;
        if (rs != "") count++;
    });
    obj.html(str);
    if (HeaderTimeObj != null) {
        HeaderTimeObj.Pause();
        HeaderTimeObj = null;
    }
    if (count >= 2)
        window.setTimeout("startMarquee()", 100);    
}
function startMarquee() { 
    HeaderTimeObj = new Marquee(thisPage + "_head_bar", 0, 0.1, 0, 40, 20, 4000, 5000, 40);    
}
/*獲取後面還會經過的站牌*/
function getNextStop() {
    if (getNextStopTime != null) {
        window.clearTimeout(getNextStopTime);
        getNextStopTime = null;
    }
    GetHTML("json", SERVER_ADDRESS + "/Service/StopList.aspx?bsid=" + BusId + "&gob=" + Goto + "&city=" + City + "&rtid=" + RouteId + "&time=" + (new Date()).getTime(), getNextStop_succeed, get_marker_error, true);
}
function getNextStop_succeed(result) {
    try {
        var list = '<option value="">不設定</option>';
        mylat = result.bus.lat;
        mylon = result.bus.lng;
        $.each(result.stop, function(index, rs) {
            list += '<option value="' + (rs.id + "," + rs.seq + "," + rs.lat + "," + rs.lng) + '">' + rs.name + '</option>';
        });
        $("#setstop").html(list);
        if (AlarmData != null) {
            var obj = document.getElementById("setstop");
            for (k = 0, l = obj.length; k < l; k++) {
                if (obj[k].text == AlarmData.name) {
                    obj[k].selected = true;
                }
            }
        }
        SetCarLocation();
    }
    catch (e) { }
    RefreshTime();
    getNextStopTime=window.setTimeout("getNextStop()", 20000);
}
/*設置到站時間*/
function SetEndStop(obj) {
    var v = obj.value.split(",");
    var _name = obj.options[obj.selectedIndex].text;
    if (obj.value == "") {
        if (AlarmData != null) {
            SetStopIco2(v[0], -1);
            AlarmData = null;
            RemoveInfo(2);
            header_info();
            //jAlert("已取消公車提醒", '樂投客公車即時資訊服務');
        }
    } else {
        SetStopIco2(v[0], 3);
        AlarmData = { id: v[0], seq: v[1], name: _name, bid: BusId,lat:v[2],lng:v[3] }
        RefreshTime();
    } 
}
/*刷新到站時間*/
function RefreshTime() {
    if (AlarmData != null) {
        GetHTML("json", SERVER_ADDRESS + "/Service/ArriveEstimable.aspx?bsid=" + AlarmData.bid + "&stid_arr=" + AlarmData.id + "&gob=" + Goto + "&city=" + City + "&time=" + (new Date()).getTime(), RefreshTimeSucceed, null, true);    
    }
}
function RefreshTimeSucceed(result) {
    RemoveInfo(2);
    var name= $("#title" + AlarmData.id).html();
    if (result.estimable_time.number <= 1) {
        jAlert("即將到達" + name + "，請準備下車", '樂投客公車即時資訊服務');
        RemoveInfo(2);
        header_info();
        SetStopIco2(AlarmData.id, -1);
        AlarmData = null;
    }
    else {
        GetHTML("json", SERVER_ADDRESS + "/Service/Weather.aspx?lat=" + AlarmData.lat + "&lng=" + AlarmData.lng, GetWeatherSucceed, null, false);
        HeaderItem[2] = '<li><span class="roteinfo">目的地' + name + '</span></li><li><span class="roteinfo">到達時間約 ' +
        result.estimable_time.number + result.estimable_time.unit + '</span></li><li><span class="roteinfo">' + weather + '</span></li>';
        //HeaderItem.push({ id: 2, msg: '<li><div style="float:left"><img src="icon/bus4.png" border="0" class="icon_bus" />' + name + '</div><div  style="float:right;padding:5px 5px 0px 0px;text-align:center">到達時間約 ' +
        //result.estimable_time.number + result.estimable_time.unit + '</div></li>'
        //});
    }
    header_info();
}